<template>
  <div class="product-add">
    <h2>新增商品</h2>
    <form @submit.prevent="handleSubmit">
      <div class="form-item">
        <label for="name">商品名称:</label>
        <input type="text" id="name" v-model="productForm.name" required />
      </div>

      <div class="form-item">
        <label for="price">价格:</label>
        <input type="number" id="price" v-model="productForm.price" step="0.01" required />
      </div>

      <div class="form-item">
        <label for="description">商品描述:</label>
        <textarea id="description" v-model="productForm.description" rows="4"></textarea>
      </div>

      <div class="form-item">
        <label for="stock">库存数量:</label>
        <input type="number" id="stock" v-model="productForm.stock" required />
      </div>

      <button type="submit">提交</button>
    </form>
    <p v-if="message" :class="{ error: isError }">{{ message }}</p>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import axios from 'axios'

export default {
  name: 'ProductAdd',
  setup() {
    const productForm = reactive({
      name: '',
      price: '',
      description: '',
      stock: '',
    })

    const message = ref('')
    const isError = ref(false)

    const handleSubmit = async () => {
      try {
        const res = await axios.post('/api/products', productForm)
        if (res.data.success) {
          message.value = '商品添加成功！'
          isError.value = false
          // 重置表单
          Object.keys(productForm).forEach((key) => (productForm[key] = ''))
        } else {
          message.value = res.data.message || '添加失败'
          isError.value = true
        }
      } catch (error) {
        message.value = '添加失败：' + error.message
        isError.value = true
      }
    }

    return {
      productForm,
      message,
      isError,
      handleSubmit,
    }
  },
}
</script>

<style scoped>
.product-add {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.form-item {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input,
textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  background-color: #4caf50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

.error {
  color: red;
}

p {
  margin-top: 15px;
}
</style>
